package com.example.infowall02.service.impl;

import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class VerificationCodeService {
    // 使用ConcurrentHashMap来存储验证码和过期时间
    private final Map<String, CodeInfo> verificationMap = new ConcurrentHashMap<>();
    // 验证码有效期（5分钟）
    private static final long EXPIRATION_TIME = 5 * 60 * 1000;
    // 验证码信息内部类
    private static class CodeInfo {
        String code;
        long expirationTime;
        CodeInfo(String code) {
            this.code = code;
            this.expirationTime = System.currentTimeMillis() + EXPIRATION_TIME;
        }
        boolean isExpired() {
            return System.currentTimeMillis() > expirationTime;
        }
    }
    // 生成随机的6位数字验证码
    public String generateVerificationCode() {
        return String.valueOf(new Random().nextInt(900000) + 100000);
    }
    // 保存验证码到Map中
    public void saveVerificationCode(String email, String code) {
        verificationMap.put(email, new CodeInfo(code));
    }
    // 验证验证码是否正确
    public boolean verify(String email, String code) {
        CodeInfo codeInfo = verificationMap.get(email);
        if (codeInfo == null || codeInfo.isExpired()) {
            verificationMap.remove(email); // 清除过期验证码
            return false;
        }
        return codeInfo.code.equals(code);
    }
}